#!/bin/bash

# AIDE 问题诊断脚本
# 用于排查常见问题和收集调试信息

set -e

echo "🔍 AIDE 系统诊断工具"
echo "===================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}ℹ️  $1${NC}"; }
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
log_error() { echo -e "${RED}❌ $1${NC}"; }
log_warning() { echo -e "${YELLOW}⚠️  $1${NC}"; }

# 系统信息
echo "📋 系统信息"
echo "----------"
echo "操作系统: $(uname -a)"
echo "当前用户: $(whoami)"
echo "当前目录: $(pwd)"
echo "时间: $(date)"
echo ""

# 检查软件版本
echo "🔧 软件版本检查"
echo "-------------"

# Node.js
if command -v node &> /dev/null; then
    log_success "Node.js: $(node --version)"
else
    log_error "Node.js 未安装"
fi

# npm
if command -v npm &> /dev/null; then
    log_success "npm: $(npm --version)"
else
    log_error "npm 未安装"
fi

# Docker
if command -v docker &> /dev/null; then
    log_success "Docker: $(docker --version)"
    
    # Docker服务状态
    if docker info &> /dev/null; then
        log_success "Docker服务运行正常"
    else
        log_error "Docker服务未运行或权限不足"
    fi
else
    log_error "Docker 未安装"
fi

# PostgreSQL客户端
if command -v psql &> /dev/null; then
    log_success "PostgreSQL客户端: $(psql --version)"
else
    log_warning "PostgreSQL客户端 未安装"
fi

echo ""

# 检查项目结构
echo "📁 项目结构检查"
echo "-------------"

if [ -f "package.json" ]; then
    log_success "根目录 package.json 存在"
else
    log_error "根目录 package.json 不存在"
fi

if [ -d "frontend" ]; then
    log_success "frontend 目录存在"
    if [ -f "frontend/package.json" ]; then
        log_success "frontend/package.json 存在"
    else
        log_error "frontend/package.json 不存在"
    fi
else
    log_error "frontend 目录不存在"
fi

if [ -d "backend" ]; then
    log_success "backend 目录存在"
    if [ -f "backend/package.json" ]; then
        log_success "backend/package.json 存在"
    else
        log_error "backend/package.json 不存在"
    fi
    
    if [ -f "backend/src/database/init.sql" ]; then
        log_success "数据库初始化脚本存在"
    else
        log_error "数据库初始化脚本不存在"
    fi
else
    log_error "backend 目录不存在"
fi

echo ""

# 检查Docker容器
echo "🐳 Docker容器检查"
echo "---------------"

if command -v docker &> /dev/null && docker info &> /dev/null; then
    # 检查AIDE相关容器
    aide_containers=$(docker ps -a --filter "name=postgres-aide" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}")
    
    if [ -n "$aide_containers" ]; then
        log_success "找到AIDE数据库容器:"
        echo "$aide_containers"
        
        # 检查容器状态
        if docker ps --filter "name=postgres-aide" | grep -q postgres-aide; then
            log_success "数据库容器正在运行"
            
            # 测试数据库连接
            if docker exec postgres-aide pg_isready -U postgres &> /dev/null; then
                log_success "数据库连接正常"
            else
                log_error "数据库连接失败"
            fi
            
            # 检查数据库列表
            echo ""
            echo "📊 数据库信息:"
            docker exec postgres-aide psql -U postgres -l 2>/dev/null || log_error "无法获取数据库列表"
            
        else
            log_warning "数据库容器已停止"
            echo "启动命令: docker start postgres-aide"
        fi
    else
        log_warning "未找到AIDE数据库容器"
        echo "创建命令示例:"
        echo "docker run --name postgres-aide -e POSTGRES_PASSWORD=password -e POSTGRES_DB=aide -p 5432:5432 -d postgres:latest"
    fi
    
    # 检查其他PostgreSQL容器
    other_postgres=$(docker ps -a --filter "ancestor=postgres" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -v postgres-aide || true)
    if [ -n "$other_postgres" ]; then
        echo ""
        log_info "其他PostgreSQL容器:"
        echo "$other_postgres"
    fi
else
    log_error "无法检查Docker容器"
fi

echo ""

# 检查端口占用
echo "🌐 端口占用检查"
echo "-------------"

ports_to_check=(3000 3001 5000 5432)

for port in "${ports_to_check[@]}"; do
    if command -v netstat &> /dev/null; then
        if netstat -tlnp 2>/dev/null | grep -q ":$port "; then
            process_info=$(netstat -tlnp 2>/dev/null | grep ":$port " | head -1)
            log_warning "端口 $port 被占用: $process_info"
        else
            log_success "端口 $port 可用"
        fi
    elif command -v ss &> /dev/null; then
        if ss -tlnp 2>/dev/null | grep -q ":$port "; then
            process_info=$(ss -tlnp 2>/dev/null | grep ":$port " | head -1)
            log_warning "端口 $port 被占用: $process_info"
        else
            log_success "端口 $port 可用"
        fi
    else
        log_warning "无法检查端口 $port (缺少netstat/ss命令)"
    fi
done

echo ""

# 检查环境变量
echo "🔐 环境变量检查"
echo "-------------"

if [ -f "backend/.env" ]; then
    log_success "backend/.env 文件存在"
    echo "内容概览:"
    grep -E "^[A-Z_]+" backend/.env | sed 's/=.*/=***/' || true
else
    log_warning "backend/.env 文件不存在"
fi

if [ -f "frontend/.env" ]; then
    log_success "frontend/.env 文件存在"
else
    log_warning "frontend/.env 文件不存在"
fi

# 检查当前环境变量
if [ -n "$DATABASE_URL" ]; then
    log_success "DATABASE_URL 已设置"
else
    log_warning "DATABASE_URL 未设置"
fi

echo ""

# 检查依赖安装
echo "📦 依赖安装检查"
echo "-------------"

# 根目录
if [ -d "node_modules" ]; then
    log_success "根目录依赖已安装"
else
    log_warning "根目录依赖未安装"
fi

# 前端
if [ -d "frontend/node_modules" ]; then
    log_success "前端依赖已安装"
else
    log_warning "前端依赖未安装"
fi

# 后端
if [ -d "backend/node_modules" ]; then
    log_success "后端依赖已安装"
else
    log_warning "后端依赖未安装"
fi

echo ""

# 检查构建文件
echo "🏗️  构建文件检查"
echo "---------------"

if [ -d "frontend/dist" ]; then
    log_success "前端构建文件存在"
    build_size=$(du -sh frontend/dist 2>/dev/null | cut -f1)
    echo "构建大小: $build_size"
else
    log_warning "前端构建文件不存在"
    echo "构建命令: npm run build:frontend"
fi

echo ""

# 日志文件检查
echo "📜 日志文件检查"
echo "-------------"

log_files=("backend/logs" "frontend/logs" "logs")
found_logs=false

for log_dir in "${log_files[@]}"; do
    if [ -d "$log_dir" ]; then
        log_success "发现日志目录: $log_dir"
        ls -la "$log_dir" 2>/dev/null || true
        found_logs=true
    fi
done

if [ "$found_logs" = false ]; then
    log_info "未发现日志文件"
fi

echo ""

# 网络连接测试
echo "🌐 网络连接测试"
echo "-------------"

# 测试本地端口
if command -v curl &> /dev/null; then
    # 测试后端健康检查
    if curl -s http://localhost:5000/api/health &> /dev/null; then
        log_success "后端服务响应正常"
    else
        log_warning "后端服务无响应"
    fi
    
    # 测试前端
    if curl -s http://localhost:3000 &> /dev/null; then
        log_success "前端服务响应正常"
    else
        log_warning "前端服务无响应"
    fi
else
    log_warning "curl未安装，无法测试HTTP连接"
fi

# 测试数据库连接
if [ -f "backend/debug-docker-db.js" ]; then
    echo ""
    log_info "运行数据库连接测试..."
    cd backend
    node debug-docker-db.js 2>/dev/null || log_error "数据库连接测试失败"
    cd ..
fi

echo ""

# 总结和建议
echo "💡 诊断总结和建议"
echo "=================="

echo ""
echo "📋 常见问题解决方案:"
echo ""
echo "1. 如果Node.js未安装:"
echo "   curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -"
echo "   sudo apt-get install -y nodejs"
echo ""
echo "2. 如果Docker未安装:"
echo "   curl -fsSL https://get.docker.com | sh"
echo "   sudo usermod -aG docker \$USER"
echo ""
echo "3. 如果依赖未安装:"
echo "   npm install"
echo "   cd frontend && npm install"
echo "   cd ../backend && npm install"
echo ""
echo "4. 如果数据库连接失败:"
echo "   docker stop postgres-aide && docker rm postgres-aide"
echo "   ./quick-setup.sh"
echo ""
echo "5. 如果端口被占用:"
echo "   sudo netstat -tlnp | grep :端口号"
echo "   kill -9 进程ID"
echo ""

echo "📞 如需更多帮助，请查看项目文档或提交Issue"
echo ""
